const Router = require("koa-router");
const { Auth } = require("@middlewares/auth");
const { Product } = require("@models/product");

const router = new Router({
  prefix: "/admin/product",
});

// 添加产品
router.post("/add", new Auth(16).m, async (ctx, next) => {
  const product = await Product.create(ctx.request.body);
  if (!product) {
    throw new global.errs.AuthFailed("添加失败");
  }
  ctx.body = {
    code: 200,
    msg: "添加成功",
    data: {},
  };
});

// 获取产品列表
router.post("/list", new Auth(16).m, async (ctx, next) => {
  const { page = 1, pageSize = 10 } = ctx.query;
  const offset = (page - 1) * pageSize;
  const where = {};
  const { count: total, rows } = await Product.findAndCountAll({
    where,
    limit: pageSize, // 每页数量
    offset, // 偏移量
  });
  ctx.body = {
    code: 200,
    msg: "获取成功",
    total,
    data: rows,
  };
});

// 更新产品
router.post("/update", new Auth(16).m, async (ctx, next) => {
  const { product_id, ...res } = ctx.request.body;
  const product = await Product.update(res, { where: { product_id } });
  if (!product) {
    throw new global.errs.AuthFailed("产品不存在");
  }

  ctx.body = {
    code: 200,
    msg: "更新成功",
    data: {},
  };
});
// 删除产品
router.post("/delete", new Auth(16).m, async (ctx, next) => {
  const { product_id } = ctx.request.body;
  const product = await Product.destroy({ where: { product_id }, focus: true });
  if (!product) {
    throw new global.errs.AuthFailed("产品不存在");
  }
  ctx.body = {
    code: 200,
    msg: "删除成功",
    data: {},
  };
});
module.exports = router;
